import { message, Popover, Upload, Spin, TimePicker, Select } from "antd";
import React, {
    useEffect,
    useLayoutEffect,
    useCallback,
    useState,
    useMemo
} from "react";
import moment from "moment";
import { connect, useDispatch } from "react-redux";
import Scrollbars from "react-custom-scrollbars";
import InfoOption from "../../../common/component/infoOption";
import SelectUserModal from "lg-select-modal";
import { LgSelect, LgPaginationA, LgInputNumber, LgDatePicker, LgSwitch, LgDrawer, LgPopLayer, LgCheckbox } from "lancoo-web-ui";
import axiosMethod from "../../../util/axios";
import "./index.scss";

function BackupsReduction(props) {
    let {
        userInfo,
        sysAddrInfo,
        visible = false,
        changeVisible = () => { }
    } = props;
    console.log(sysAddrInfo)
    const [baseInfo, setBaseInfo] = useState({});
    const [backData, setBackData] = useState({});
    const [remindInfo, setRemindInfo] = useState({});
    const [chooseList, setChooseList] = useState([]);

    const [selectUserVisible, setSelectUserVisible] = useState(false);


    const getBaseInfo = useCallback(() => {
        axiosMethod({
            type: "get",
            baseUrl: sysAddrInfo["491"]?.webSvrAddr,
            url: "api/backupRestore/setting/getBaseSetting",
            body: {
                eduId: userInfo.eduId
            },
            callback: function (res, info) {
                if (!res || info.code !== "200") {
                    return;
                }
                setBaseInfo(res);
            }
        });
    }, [userInfo]);

    const getRemindInfo = useCallback(() => {
        axiosMethod({
            type: "get",
            baseUrl: sysAddrInfo["491"]?.webSvrAddr,
            url: "api/backupRestore/setting/getMsgSetting",
            body: {
                eduId: userInfo.eduId
            },
            callback: function (res, info) {
                if (!res || info.code !== "200") {
                    return;
                }
                if (res.msgType.indexOf("4") > -1) {
                    res.toEmail = true;
                }
                res.msgType = res.msgType.split(',').filter(item => item !== "4");
                res.mailAddress = res.mailAddress[0];
                setChooseList(res.noticeRemindObjectInfo || []);
                setRemindInfo(res);
            }
        });
    }, [userInfo]);

    const getBackData = useCallback(() => {
        axiosMethod({
            type: "get",
            baseUrl: sysAddrInfo["491"]?.webSvrAddr,
            url: "api/backupRestore/scheduleTask/getScheduleTask",
            noCheck: true,
            body: {
                taskMethod: 'backUpDatabaseJob'
            },
            callback: function (res, info) {
                if (!res || info.code !== "200") {
                    return;
                }
                res.backupTime = res.taskStartTime.substr(0, 5);
                setBackData(res);
            }
        });
    }, []);

    const editBaseInfo = (key, value) => {
        let info = { ...baseInfo };
        info[key] = value;
        setBaseInfo(info);
    }

    const editBackData = (key, value) => {
        let info = { ...backData };
        // if (key === "backupTime") {
        //     console.log(key)
        //     console.log(value)
        //     value = moment(value).format("HH:mm");
        // }
        info[key] = value;
        setBackData(info);
    }

    const editRemindInfo = (key, value) => {
        let info = { ...remindInfo };
        info[key] = value;
        if (key === "toEmail" && !value) {
            info.mailAddress = "";
        }
        setRemindInfo(info);
    }

    const selectUserChange = (value) => {
        setSelectUserVisible(value);
    }

    const getSelectList = (info) => {
        setChooseList(info.selectUserList);
    }

    const deleteChooseList = () => { }

    const sendBaseInfo = useCallback(() => {
        return new Promise((resolve, reject) => {
            axiosMethod({
                type: "post",
                baseUrl: sysAddrInfo["491"]?.webSvrAddr,
                url: "api/backupRestore/setting/save/baseSetting",
                body: {
                    ...baseInfo,
                    eduId: userInfo.eduId
                },
                callback: function (res, info) {
                    if (info.code === "200") {
                        resolve(true);
                        return;
                    }
                    resolve("");
                }
            });
        })
    }, [userInfo, baseInfo]);

    const sendBackData = useCallback(() => {
        return new Promise((resolve, reject) => {
            axiosMethod({
                type: "post",
                baseUrl: sysAddrInfo["491"]?.webSvrAddr,
                url: "api/backupRestore/scheduleTask/updateTask",
                body: {
                    taskId: backData.taskId,
                    interval: backData.frequency,
                    taskType: 2,
                    taskStartTime: backData.backupTime + ":00"
                },
                callback: function (res, info) {
                    if (info.code === "200") {
                        axiosMethod({
                            type: "post",
                            baseUrl: sysAddrInfo["491"]?.webSvrAddr,
                            url: "api/backupRestore/scheduleTask/updateTaskTurnBo",
                            body: {
                                taskId: backData.taskId,
                                taskMethod: "backUpDatabaseJob",
                                status: backData.beTurn
                            },
                            callback: function (res, info) {
                                if (info.code === "200") {
                                    resolve(true);
                                    return;
                                }
                                resolve("");
                            }
                        });
                        return;
                    }
                    resolve("");
                }
            });

        })
    }, [backData]);

    const sendRemindInfo = useCallback(() => {
        return new Promise((resolve, reject) => {
            let msgType = remindInfo.msgType.sort();
            if (remindInfo.toEmail) {
                msgType.push("4");
            }
            axiosMethod({
                type: "post",
                baseUrl: sysAddrInfo["491"]?.webSvrAddr,
                url: "api/backupRestore/setting/save/msgSetting",
                body: {
                    ...remindInfo,
                    eduId: userInfo.eduId,
                    msgType: msgType.join(","),
                    noticeRemindObject: chooseList.map(item => item.userId),
                    mailAddress: [remindInfo.mailAddress]
                },
                callback: function (res, info) {
                    if (info.code === "200") {
                        resolve(true);
                        return;
                    }
                    resolve("");
                }
            });
        })
    }, [userInfo, chooseList, remindInfo]);

    const sendSettingData = useCallback(() => {
        if (!baseInfo.backUpSavePath) {
            message.warn("备份保存路径不能为空");
            return;
        }
        if (!/^(?:(?:[a-zA-Z]:|\.{0,2})?[\\/](?:[^\\?/*|<>:"]+[\\/])*)(?:(?:[^\\?/*|<>:"]+?)(?:\.[^.\\?/*|<>:"]+)?)?$/.test(baseInfo.backUpSavePath)) {
            message.warn("备份保存路径格式不正确");
            return;
        }
        if (!chooseList.length) {
            message.warn("通知提醒人员不能为空");
            return;
        }
        if (!remindInfo.msgType?.length) {
            message.warn("通知提醒方式不能为空");
            return;
        }
        if (remindInfo.toEmail && !remindInfo.mailAddress) {
            message.warn("接收邮件地址不能为空");
            return;
        }
        if (remindInfo.toEmail && remindInfo.mailAddress && !/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(remindInfo.mailAddress)) {
            message.warn("接收邮件地址格式不正确");
            return;
        }
        Promise.all([sendBaseInfo(), sendBackData(), sendRemindInfo()])
            .then((data) => {
                console.log(data, 'all结果')
                if (Array.isArray(data)) {
                    if (data[0]) { message.success("备份基础设置成功"); }
                    if (data[1]) { message.success("自动备份设置成功"); }
                    if (data[2]) { message.success("备份通知提醒设置成功"); }
                    if (data.every(item => item === true)) {
                        changeVisible(false);
                    }
                }
            })
    }, [baseInfo, chooseList, remindInfo, changeVisible, sendBaseInfo, sendBackData, sendRemindInfo]);

    const uploadDirectory = async () => {
        const handle = await window.showDirectoryPicker();
        const ent = await handle.entries();
        for await (const item of ent) {
            console.log(item);
        }
    }

    useEffect(() => {
        getBaseInfo();
        getBackData();
        getRemindInfo();
    }, [getBaseInfo, getBackData, getRemindInfo]);

    return (
        <LgDrawer
            type={"right"}
            width={800}
            className="setting-drawer"
            title="备份设置"
            visible={visible}
            checkBtn={sendSettingData}
            closeBtn={(value) => {
                changeVisible(false);
            }}>
            <div className="drawer-option-group">
                <p className="drawer-option-title">备份基础设置</p>
                <div className="drawer-option-one">
                    <span className="drawer-option-one-name">备份保存路径:</span>
                    <input
                        className="drawer-iption-one-input"
                        value={baseInfo.backUpSavePath}
                        type="text"
                        maxLength={100}
                        onChange={(e) => editBaseInfo("backUpSavePath", e.target.value)}
                        placeholder="请输入..." />
                    {/* <div className="drawer-btn" onClick={uploadDirectory}>选择目录</div> */}
                </div>
                <div className="drawer-option-one">
                    <span className="drawer-option-one-name">备份最多保存份数:</span>
                    <LgInputNumber
                        max={3}
                        min={1}
                        value={baseInfo.backUpFileNum || 1}
                        onChange={(value) => editBaseInfo("backUpFileNum", value)}
                        size='small'></LgInputNumber>
                    <span className="drawer-option-tip">(提示: 超过保存份数，再次备份时将自动删除其他历史备份记录)</span>
                </div>
            </div>
            <div className="drawer-option-group">
                <p className="drawer-option-title">自动备份设置</p>
                <div className="drawer-option-one">
                    <span className="drawer-option-one-name">是否开启自动备份:</span>
                    <LgSwitch
                        size="small"
                        checked={backData.beTurn === "1" ? true : false}
                        onClick={() => editBackData("beTurn", backData.beTurn === "1" ? "0" : "1")} />
                </div>
                <div className="drawer-option-one">
                    <span className="drawer-option-one-name">备份周期:</span>
                    <div className="drawer-option-value">
                        每隔
                        <LgInputNumber
                            className="backup-time"
                            max={30}
                            value={backData.frequency || 1}
                            min={1}
                            onChange={(value) => editBackData("frequency", value)}
                            size='small'></LgInputNumber>
                        天进行自动备份
                    </div>
                </div>
                <div className="drawer-option-one">
                    <span className="drawer-option-one-name">备份时间点:</span>
                    {backData.backupTime && (
                        <LgDatePicker
                            type="C"
                            start="03:00"
                            step="00:15"
                            end="05:00"
                            onChange={(value) => editBackData("backupTime", value)}
                            value={moment(`${moment().format("YYYY-MM-DD")} ${backData.backupTime}`).toDate()}
                        />
                    )}
                    {/* <Select
                        value={backData.backupTime}
                        onChange={(value) => editBackData("backupTime", value)}
                        placeholder="请选择备份时间"
                        // size="small"
                        style={{ minWidth: 120 }}
                        // suffixIcon={<ClockCircleOutlined />}
                        // showSearch
                        filterOption={(input, option) =>
                            option.children.toLowerCase().includes(input.toLowerCase())
                        }
                    >
                        {(() => {
                            const options = [];
                            for (let hour = 0; hour < 24; hour++) {
                                for (let minute = 0; minute < 60; minute += 15) {
                                    const timeStr = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
                                    options.push(
                                        <Select.Option key={timeStr} value={timeStr}>
                                            {timeStr}
                                        </Select.Option>
                                    );
                                }
                            }
                            return options;
                        })()}
                    </Select> */}
                </div>
            </div>
            <div className="drawer-option-group">
                <p className="drawer-option-title">备份通知提醒设置</p>
                <div className="drawer-option-one" style={{ alignItems: "inherit", marginBottom: 16 }}>
                    <span className="drawer-option-one-name" style={{ lineHeight: '48px' }}>通知提醒人员:</span>
                    <div className="drawer-option-area">
                        <Scrollbars autoHeight autoHeightMax={160}>
                            <ul className="option-user-list">
                                {
                                    chooseList.map((item, index) => (
                                        <li key={index} title={`${item.userName}(${item.userId})`}>
                                            {item.userName}
                                            <span>({item.userId})</span>
                                            <i className="deletelogo" onClick={() => deleteChooseList(index)}></i>
                                        </li>
                                    ))
                                }
                            </ul>
                        </Scrollbars>
                        <div className="option-user-info">
                            {
                                chooseList.length ?
                                    <span className="info_text">
                                        已选择<span>{chooseList.length}</span>人
                                    </span> :
                                    ""
                            }
                            <span className="choose_btn" onClick={() => setSelectUserVisible(true)}>{chooseList.length > 0 ? "修改" : "选择"}</span>
                            <span className="clear_btn" onClick={() => setChooseList([])}>清空</span>
                        </div>
                    </div>
                </div>
                <InfoOption
                    optionName="通知提醒方式"
                    type="checkbox"
                    value={remindInfo.msgType}
                    getVal={(value) => editRemindInfo("msgType", value)}
                    list={[{ key: "1", name: "微信公众号消息" }, { key: "2", name: "通知" }, { key: "3", name: "系统提醒" }]} />
                <div className="drawer-option-one" style={{ marginBottom: 16 }}>
                    <span className="drawer-option-one-name">邮件提醒:</span>
                    <LgSwitch
                        size="small"
                        onClick={() => editRemindInfo("toEmail", remindInfo.toEmail ? false : true)}
                        checked={remindInfo.toEmail} />
                </div>
                {
                    remindInfo.toEmail ?
                        <div className="drawer-option-one">
                            <span className="drawer-option-one-name">接收邮件地址:</span>
                            <input
                                className="drawer-iption-one-input"
                                value={remindInfo.mailAddress}
                                type="text"
                                onChange={(e) => editRemindInfo('mailAddress', e.target.value)}
                                placeholder="请输入..." />
                        </div> :
                        ""
                }

            </div>

            {/* <SelectUserModal 
            baseUrl={sysAddrInfo["260"]?.webSvrAddr}
            maxLength={100}
            visible={selectUserVisible}
            schoolId={userInfo.schoolId}
            token={sessionStorage.getItem("token")}
            zIndex={4000}
            getSelectResult={getSelectList}
            selectList={chooseList}
            changeVisible={selectUserChange}/> */}

            {/* {selectUserVisible && sysAddrInfo["264"]?.webSvrAddr && ( */}

            <SelectUserModal
                baseUrl={sysAddrInfo["264"]?.webSvrAddr}
                maxLength={500}
                type={'edu'}
                visible={selectUserVisible}
                token={sessionStorage.getItem("token")}
                zIndex={4000}
                getSelectResult={getSelectList}
                selectList={chooseList}
                changeVisible={selectUserChange}
            />
            {/* )} */}

        </LgDrawer>
    )
}
const mapToProps = (state) => {
    return {
        sysAddrInfo: state.sysAddrInfo,
        userInfo: state.userInfo,
        getTextById: state.getTextById,
        alertInfo: state.alertInfo
    }
}
export default connect(mapToProps)(BackupsReduction);